package com.kunbo.offer.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.kunbo.offer.entity.FanFile;
import com.kunbo.offer.service.FanFileService;
import com.kunbo.offer.service.FanSupplementParamService;
import com.shuohe.util.excel.ExcelUtils;
import com.shuohe.util.returnBean.ReturnBean;
import com.shuohe.util.uuid.UUID;

@RestController
@RequestMapping("/fanFile/")
@Slf4j
public class FanFileController {
	@Autowired
	private FanSupplementParamService fanSupplementParamService;
	// 文件写入路径
	@Value("${myPath.filePath}")
	private String filePath;
	@Autowired
	private FanFileService fanFileService;
	// 调用路径
	@Value("${myPath.rfPath}")
	private String rfPath;

	@RequestMapping(value = "uploadFanFile", method = RequestMethod.POST)
	public ReturnBean uploadFanFile(HttpServletRequest request,
			@RequestParam("fileType") String fileType,
			@RequestParam("fanNumber") String fanNumber) {
		if (fileType.equals("外形图")) {
			fanFileService.deleteByNumberAndType(fanNumber, "外形图");
		}
		List<FanFile> fileList = new ArrayList<FanFile>();
		List<MultipartFile> files = ((MultipartHttpServletRequest) request)
				.getFiles("file");
		MultipartFile file = null;
		BufferedOutputStream stream = null;
		System.out.println(files.size());
		System.out.println(fileType);
		System.out.println(fanNumber);
		for (int i = 0; i < files.size(); ++i) {
			FanFile fanFile = new FanFile();
			file = files.get(i);
			String fileName = file.getOriginalFilename();
			log.info("上传的文件名为：" + fileName);
			// 获取文件的后缀名
			String suffixName = fileName.substring(fileName.lastIndexOf("."));
			log.info("文件的后缀名为：" + suffixName);
			// 生成一个唯一的文件名称
			fileName = UUID.genImageName() + fileName;
			if (!file.isEmpty()) {
				try {
					byte[] bytes = file.getBytes();
					stream = new BufferedOutputStream(new FileOutputStream(
							new File(filePath + fileName)));// 设置文件路径及名字
					stream.write(bytes);// 写入
					stream.close();
				} catch (Exception e) {
					stream = null;
					return new ReturnBean(false, "文件上传错误，请联系管理员");
				}
			} else {
				return new ReturnBean(false, "文件为空请检测");
			}
			fanFile.setFan_number(fanNumber);
			fanFile.setFileType(fileType);
			fanFile.setFileName(fileName);
			fanFile.setFileSuffix(suffixName);
			fanFile.setFilePath(filePath + fileName);
			fanFile.setFileRealPath(rfPath + fileName);
			fileList.add(fanFile);
		}
		fanFileService.save(fileList);
		return new ReturnBean(true, "文件上传成功");

	}

	/**
	 * 选型导入Excel
	 * 
	 * @param request
	 *            接收文件
	 * @param typeId
	 *            接收的类型
	 * @return
	 */
	@RequestMapping(value = "importFanParams", method = RequestMethod.POST)
	public ReturnBean importFanParams(HttpServletRequest request,
			@RequestParam("typeId") String typeId) {
		if (StringUtils.isBlank(typeId)) {
			return new ReturnBean(false, "请选择产品分类！");
		}
		// List<FanFile> fileList = new ArrayList<FanFile>();
		List<MultipartFile> files = ((MultipartHttpServletRequest) request)
				.getFiles("file");
		MultipartFile file = null;
		BufferedOutputStream stream = null;
		String fileName = "";
		for (int i = 0; i < files.size(); ++i) {
			// FanFile fanFile = new FanFile();
			file = files.get(i);
			fileName = file.getOriginalFilename();
			log.info("上传的文件名为：" + fileName);
			// 获取文件的后缀名
			String suffixName = fileName.substring(fileName.lastIndexOf("."));
			if (!suffixName.equals(".xls")) {
				return new ReturnBean(false, "只允许上传EXCEL中后缀为xls（97-2003版）！");
			}
			log.info("文件的后缀名为：" + suffixName);
			// 生成一个唯一的文件名称
			fileName = UUID.genImageName() + fileName;
			if (!file.isEmpty()) {
				try {
					byte[] bytes = file.getBytes();
					stream = new BufferedOutputStream(new FileOutputStream(
							new File(filePath + fileName)));// 设置文件路径及名字
					stream.write(bytes);// 写入
					stream.close();
				} catch (Exception e) {
					stream = null;
					return new ReturnBean(false, "文件上传错误，请联系管理员");
				}
			} else {
				return new ReturnBean(false, "文件为空请检测");
			}
			/*
			 * fanFile.setFan_number(fanNumber); fanFile.setFileType(fileType);
			 * fanFile.setFileName(fileName); fanFile.setFileSuffix(suffixName);
			 * fanFile.setFilePath(filePath + fileName);
			 * fanFile.setFileRealPath(rfPath+fileName); fileList.add(fanFile);
			 */
		}
		String fileRealPath = filePath + fileName;
		System.err.println("上传的路径是：" + fileRealPath);
		// fanFileService.save(fileList);
		File eFile = new File(fileRealPath.replace("/", File.separator));
		if (!eFile.exists()) {
			return new ReturnBean(false, "上传有误！");
		}

		String[][] datas = null;
		try {
			datas = ExcelUtils.getData(eFile, 1, 65530);// 5000 行
			fanSupplementParamService.importExcel(datas,typeId);
		} catch (Exception e) {
			return new ReturnBean(false, e.toString());
		}
		return new ReturnBean(true, "");

	}

	/**
	 * 根据文件的路径下载文件
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/downloadFile.do")
	public String downloadFile(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// String fileName = "region.xls";
		String realPath = request.getParameter("fileRealPath");// 设置文件名，根据业务需要替换成要下载的文件名
		String fileName = request.getParameter("fileName");//
		if (realPath != null) {
			// 设置文件路径
			File file = new File(realPath);
			if (file.exists()) {
				response.setContentType("application/force-download");// 设置强制下载不打开
				// response.addHeader("Content-Disposition",
				// "attachment;fileName=" + fileName);// 设置文件名
				response.setHeader(
						"Content-Disposition",
						"attachment; fileName=" + fileName + ";"
								+ "filename*=utf-8''"
								+ URLEncoder.encode(fileName, "UTF-8")); // 设置中文名称并且解决中文乱码问题
				byte[] buffer = new byte[1024];
				FileInputStream fis = null;
				BufferedInputStream bis = null;
				try {
					fis = new FileInputStream(file);
					bis = new BufferedInputStream(fis);
					OutputStream os = response.getOutputStream();
					int i = bis.read(buffer);
					while (i != -1) {
						os.write(buffer, 0, i);
						i = bis.read(buffer);
					}
					System.out.println("success");
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (bis != null) {
						try {
							bis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (fis != null) {
						try {
							fis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return null;
	}

	/**
	 * 查看图片
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/preview.do")
	public void preview(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// String fileName = "region.xls";
		String fanNumber = request.getParameter("fan_number");// 编号
		// String fileType = request.getParameter("fileType");// 编号
		List<FanFile> fileList = fanFileService.findListByFanNumberAndFileType(
				fanNumber, "外形图");
		if (fileList != null && fileList.size() > 0) {
			String realPath = fileList.get(0).getFilePath();// 设置文件名，根据业务需要替换成要下载的文件名

			File file = new File(realPath);
			if (!file.exists()) {
				return;
			}
			FileInputStream fis = null;
			try {
				fis = new FileInputStream(file);
				byte[] buffer = new byte[1024];
				while (fis.read(buffer) > 0) {
					response.getOutputStream().write(buffer);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (fis != null) {
					try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	@RequestMapping("/delete.do")
	public void delete(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// String fileName = "region.xls";
		String fanNumber = request.getParameter("fan_number");// 编号
		fanFileService.deleteByNumberAndType(fanNumber, "外形图");
	}

}
